package com.example.stretching;

import java.io.ObjectOutputStream.PutField;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.example.db.DLog;
import com.example.db.DbopenHelper;
import com.example.stretching.AlarmAdapter.ViewHolder;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.internal.mh;

/**
 * 
 * 진짜 메인은 절대아님!!!!!!!!! 처음 하던거랑 구조가 바뀌어서 이름만 Main;
 * insert하는 클래스로 Add 했을 때 구현되는 클래스
 * 시작시간 끝나는 시간을 설정해서 DB에 저장
 * 알람을 ON시켜놔도 리스트를 클릭해서 확인을 해야 알람을 확인시켜서 설정할수있음! 
 * @author DS
 *
 */
public class MainActivity extends Activity{
//	public static String PROJECT_ID = "macro-mender-706";
	
	TextView textView1, textView2, textView3;
	protected static Cursor mCursor;

	Button frombtn, tobtn, setbtn;

	static ArrayList<AlarmData> arrayListAlarmTimeItem;
	LayoutInflater inflater;



	private static final String TAG = "TestDataBaseActivity";

	private Context mContext;

	protected ToggleButton mon_, tue_, wed_, thu_, fri_, sat_, sun_;
	protected static Switch switch_on_off;
	Calendar datetime = Calendar.getInstance();

	static final GregorianCalendar gregorianCalendar = new GregorianCalendar(
			TimeZone.getTimeZone("GMT+09:00"));
	static final GregorianCalendar gregorianCalendar2 = new GregorianCalendar(
			TimeZone.getTimeZone("GMT+09:00"));
	private DbopenHelper mDbOpenHelper;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.include_main);
		setLayout();
//		registerGcm();
		mContext = getApplicationContext();

		mDbOpenHelper = new DbopenHelper(this);
		mDbOpenHelper.open();

		AlarmAdapter.arrayAdapterAlarmList = new AlarmAdapter(mContext,
				arrayListAlarmTimeItem);


		arrayListAlarmTimeItem = new ArrayList<AlarmData>();

		AlarmAdapter.arrayAdapterAlarmList = new AlarmAdapter(this, arrayListAlarmTimeItem);

		mon_ = (ToggleButton) findViewById(R.id.toggle_mon);
		tue_ = (ToggleButton) findViewById(R.id.toggle_tue);
		wed_ = (ToggleButton) findViewById(R.id.toggle_wed);
		thu_ = (ToggleButton) findViewById(R.id.toggle_thu);
		fri_ = (ToggleButton) findViewById(R.id.toggle_fri);
		sat_ = (ToggleButton) findViewById(R.id.toggle_sat);
		sun_ = (ToggleButton) findViewById(R.id.toggle_sun);
		
		mon_.setChecked(true);
		tue_.setChecked(true);
		wed_.setChecked(true);
		thu_.setChecked(true);
		fri_.setChecked(true);
		
		textView1 = (TextView) findViewById(R.id.timeText1);
		textView2 = (TextView) findViewById(R.id.timeText2);
		
		
		switch_on_off = (Switch) findViewById(R.id.switch_on_off);
		switch_on_off.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
 			//
 						public void onCheckedChanged(CompoundButton cb, boolean isChecking) {
 							if (isChecking) {
 								ContentValues values = new ContentValues();
 								savePreferences("switch_Value", switch_on_off.isChecked());
// 								 savePreferences("switch_Value", switch_on_off.isChecked());
 								String onoff = "ON";
 								AlarmAdapter.onoff = onoff;
 								arrayListAlarmTimeItem.clear();
 								doWhileCursorToArray.doWhileCursorToArray();
 								AlarmAdapter.arrayAdapterAlarmList.setArrayList(arrayListAlarmTimeItem);
 								AlarmAdapter.arrayAdapterAlarmList.notifyDataSetChanged();

 								mCursor.close();
 								
 						} else {
								savePreferences("switch_Value", switch_on_off.isChecked());
						     String onoff2 = "OFF";
 							AlarmAdapter.onoff = onoff2;
 							arrayListAlarmTimeItem.clear();
								doWhileCursorToArray.doWhileCursorToArray();
								AlarmAdapter.arrayAdapterAlarmList.setArrayList(arrayListAlarmTimeItem);
								AlarmAdapter.arrayAdapterAlarmList.notifyDataSetChanged();

								mCursor.close();
 						}

 						}
 		});
		AlarmAdapter.arrayAdapterAlarmList = new AlarmAdapter(this, arrayListAlarmTimeItem);

		modifyScheduleActivity.alarmManager = (AlarmManager) getApplicationContext().getSystemService(
				Context.ALARM_SERVICE);
		modifyScheduleActivity.alarmManager.setTimeZone("GMT+09:00");

//		MainActivity.mListView.setAdapter(mAdapter);

		doWhileCursorToArray.doWhileCursorToArray();


		frombtn = (Button) findViewById(R.id.from);
		frombtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new TimePickerDialog(MainActivity.this, t, datetime
						.get(Calendar.HOUR_OF_DAY), datetime
						.get(Calendar.MINUTE), true).show();
				AlarmAdapter.mHour = datetime.get(Calendar.HOUR_OF_DAY);
				AlarmAdapter.mMinute = datetime.get(Calendar.MINUTE);

			}

			TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {

				@Override
				public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
					// TODO Auto-generated method stub
					gregorianCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
					gregorianCalendar.set(Calendar.MINUTE, minute);
					AlarmAdapter.mHour = hourOfDay;
					AlarmAdapter.mMinute = minute;
					textView1.setText(String.format("%d시 %d분", hourOfDay,
							minute));

				}
			};

		});

		tobtn = (Button) findViewById(R.id.to);

		tobtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new TimePickerDialog(MainActivity.this, t2, datetime
						.get(Calendar.HOUR_OF_DAY), datetime
						.get(Calendar.MINUTE), true).show();
				// mHour = datetime.get(Calendar.HOUR_OF_DAY);
				// mMinute = datetime.get(Calendar.MINUTE);
				AlarmAdapter.mHour2 = datetime.get(Calendar.HOUR_OF_DAY);
				AlarmAdapter.mMinute2 = datetime.get(Calendar.MINUTE);

			}

			TimePickerDialog.OnTimeSetListener t2 = new TimePickerDialog.OnTimeSetListener() {

				@Override
				public void onTimeSet(TimePicker view, int hourOfDay2, int minute) {
					// TODO Auto-generated method stub
					gregorianCalendar2.set(Calendar.HOUR_OF_DAY, hourOfDay2);
					gregorianCalendar2.set(Calendar.MINUTE, minute);
				
					AlarmAdapter.mHour2 = hourOfDay2;
					AlarmAdapter.mMinute2 = minute;
					textView2.setText(String.format("%d시 %d분", hourOfDay2,
							minute));
				}
			};

		});

		setbtn = (Button) findViewById(R.id.set);
	
		setbtn.setOnClickListener(new View.OnClickListener() {
		
			public void onClick(View v) {

				
//						Intent intent = new Intent(MainActivity.this,
//								AlarmAdapter.class); // AlarmReceive.class이클레스는 따로 만들꺼임
//														// 알람이 발동될때 동작하는 클레이스임
//						
//						Calendar calendar = Calendar.getInstance();
				try{
						if (mon_.isChecked()) {
							AlarmAdapter.mMon = "월";
						} else {
							AlarmAdapter.mMon = "";
						};
						if (tue_.isChecked()) {
							AlarmAdapter.mTue = "화";
						} else {
							AlarmAdapter.mTue = "";
						};
						if (wed_.isChecked() == true) {
							AlarmAdapter.mWed = "수";
						} else {
							AlarmAdapter.mWed = "";
						};
						if (thu_.isChecked() == true) {
							AlarmAdapter.mThu = "목";
						} else {
							AlarmAdapter.mThu = "";
						};
						if (fri_.isChecked() == true) {
							AlarmAdapter.mFri = "금";
						} else {
							AlarmAdapter.mFri ="";
						};
						if (sat_.isChecked() == true) {
							AlarmAdapter.mSat ="토";
						} else {
							AlarmAdapter.mSat= "";
						};
						if (sun_.isChecked() == true) {
							AlarmAdapter.mSun = "일";
						} else {
							AlarmAdapter.mSun = "";
						};
						if(switch_on_off.isChecked() == true){
							AlarmAdapter.onoff = "ON";
							Log.d("ON",AlarmAdapter.onoff);
						} else if(switch_on_off.isChecked() == false){
							AlarmAdapter.onoff = "OFF";
						}
						Calendar cal = Calendar.getInstance();

						boolean[] week_ = { false, AlarmAdapter.mMon.equals("월"), 
								AlarmAdapter.mTue.equals("화"),
								AlarmAdapter.mWed.equals("수"),
								AlarmAdapter.mThu.equals("목"),
								AlarmAdapter.mFri.equals("금"),
								AlarmAdapter.mSat.equals("토"),
								AlarmAdapter.mSun.equals("일") }; // sunday=1 이라서 0의
						
				mDbOpenHelper.insertColumn(

						AlarmAdapter.mMon, AlarmAdapter.mTue, AlarmAdapter.mWed, 
						AlarmAdapter.mThu, AlarmAdapter.mFri, AlarmAdapter.mSat, AlarmAdapter.mSun,
				// boolean[] week{2},
				// a1, a2, a3, a4, a5, a6, a7,

						AlarmAdapter.mHour, 
						AlarmAdapter.mMinute, 
						AlarmAdapter.mHour2, 
						AlarmAdapter.mMinute2,
						AlarmAdapter.onoff
					

				);
				arrayListAlarmTimeItem.clear();

				
				// RealMainActivity.arrayListAlarmTimeItem2.clear();

				doWhileCursorToArray.doWhileCursorToArray();
				AlarmAdapter.arrayAdapterAlarmList.setArrayList(arrayListAlarmTimeItem);
				AlarmAdapter.arrayAdapterAlarmList.notifyDataSetChanged();

				mCursor.close();
				//
				// break;
				
				Toast.makeText(getApplicationContext(), "Data Saved!",
						Toast.LENGTH_SHORT).show();
				finish();
            	Intent intent11 = new Intent(MainActivity.this, tabMainActivity.class);
            	startActivity(intent11);

				} catch(Exception e) {
					finish();
			
				}
			}
			
		});
		}       
		
	  private void savePreferences(String key, boolean value) {
          SharedPreferences sharedPreferences = PreferenceManager
                  .getDefaultSharedPreferences(this);
          Editor editor = sharedPreferences.edit();
          editor.putBoolean(key, value);
          editor.commit();
      }
	private void setLayout() {
        tabMainActivity.tabHost = (TabHost) findViewById(android.R.id.tabhost);

		
	}
	@Override
	protected void onDestroy() {
		mDbOpenHelper.close();
		super.onDestroy();

	}
}


